package com.codeduck.curator.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-05-18
 */
@Configuration
public class ZkConfig {
    private String zkAddress = "192.168.124.24:2181";
    private int sessionTimeout = 60000; // 会话超时时长 ms
    private int connectionTimeout = 15000; // 连接超时时长 ms
    private String nameSpace = "zk-curator-service"; // 客户端默认操作为zk的根节点，此处定义该服务的节点名称
    private String lockNode = "/zk-lock"; // 分布式锁节点
    private int baseSleepTimeMs = 3000; // 重试间隔时长
    private int maxRetries = 10; // 重试次数


    @Bean(initMethod = "start", destroyMethod = "close")
    public CuratorFramework curatorFramework() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
        return CuratorFrameworkFactory.builder()
                .connectString(zkAddress)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(connectionTimeout)
                .retryPolicy(retryPolicy)
                .namespace(nameSpace)
                .build();
    }
}